import configparser
import os
import sys
import time
import traceback
import warnings

import redis


def RedisConnect(cur_path, dbConfigFileName=None,sesc="proxy", encoding="utf-8"):
    """
    连接数据库 通过读取配置文件连接,如果读取配置文件 失败  返回None
    :return:
    """
    if not cur_path:
        warnings.warn("MajorDbConnect config path err,get default path config,That may be a mistake")
        global curPath
    else:
        curPath = cur_path
    cf = configparser.ConfigParser()
    if dbConfigFileName:
        curPath = os.path.join(curPath, dbConfigFileName)
    try:
        cf.read(curPath, encoding=encoding)
    except:
        print('读取配置失败:' + traceback.format_exc())
        sys.exit(-1)
    if cf:
        RedisHost = cf.get(sesc, 'RedisHost')
        RedisPort = cf.get(sesc, 'RedisPort')
        RedisDB = cf.get(sesc, 'RedisDB')
        RedisKey = cf.get(sesc, 'RedisKey')
        try:
            rconn = redis.StrictRedis(host=RedisHost, port=RedisPort, db=RedisDB, decode_responses=True)
        except:
            # 有可能因为网络波动无法连接 这里休眠10秒重连一次  如果还是失败就放弃
            time.sleep(10)
            rconn = redis.StrictRedis(host=RedisHost, port=RedisPort, db=RedisDB, decode_responses=True)
        if rconn:
            return rconn, RedisKey
    return None


def getDataFromRedis(curPath, dbConfigFileName=None,sesc="proxy"):
    rconn, RedisKey = RedisConnect(curPath, dbConfigFileName,sesc=sesc)
    if rconn:
        rows = rconn.smembers(RedisKey)
        return rows
    else:
        print("redis出现连接错误")
        sys.exit(-1)
